package com.zone.module_base.viewmodel

import android.util.Log
import androidx.databinding.ObservableField
import androidx.databinding.ObservableFloat
import androidx.lifecycle.MutableLiveData
import com.zone.core.base.BaseViewModel
import com.zone.core.helper.FileHelper

class TestFunctionViewModel(val str: String) : BaseViewModel() {

    val TAG = "TestFunctionViewModel"
    val progress = ObservableFloat(0f)
    val fileSize = ObservableField("")
    val fileTotalLength = ObservableField("")
    val writeContent = ObservableField<String>("")
    val readContent = ObservableField("")
    val speed = ObservableField("")

    val selectFileType = MutableLiveData(0)

    init {
        Log.d(TAG, "===================: $str")
        postEvent(6)
    }

    fun onClick(type: Int) {
        postEvent(type)
    }

    //文件操作
    fun fileOperation(type: Int) {
        when (type) {
            1 -> {//保存
                if (selectFileType.value == 2) {
                    postEvent(4)
                } else {
                    saveToFile()
                }
            }

            2 -> {//读取
                readFileContent()
            }

            3 -> {//读取asset

            }
        }
    }

    fun saveToFile() {
        launchIO {
            when (selectFileType.value) {
                0 -> {
                    FileHelper.writeInternalFile("test.txt", writeContent.get()!!)
                }
                1 -> {
                    FileHelper.writeDataToExternalStorage("test.txt", writeContent.get()!!)
                }
                2 -> {
                    FileHelper.writeDataToExternalPublicStorage("test.txt", writeContent.get()!!)
                }
            }
        }
    }

    fun readFileContent() {
        readContent.set("")
        launchIO {
            var value = ""
            when (selectFileType.value) {
                0 -> {
                    value = FileHelper.readInternalFile("test.txt")
                }

                1 -> {
                    value = FileHelper.readDataFromExternalStorage("test.txt")
                }

                2 -> {
                    FileHelper.readDataFromExternalPublicStorage("test.txt")?.let {
                        value = it
                    }
                }
            }
            readContent.set(value)
        }
    }
}